/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.core.validation.requiredvaladaptor;


import com.inspur.edp.cef.api.message.CefException;
import com.inspur.edp.cef.entity.dependenceTemp.DataValidator;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import io.iec.edp.caf.commons.exception.ExceptionLevel;
import org.springframework.util.StringUtils;

public class RequiredAssoValAdaptor extends RequiredValAdaptor<Object>
{
	private String foreignKeyName;
	private java.lang.Class assoType;

	public RequiredAssoValAdaptor(String propName, String foreignKeyName, java.lang.Class assoType)
	{
		super(propName);
		DataValidator.checkForEmptyString(foreignKeyName, "foreignKeyName");
		DataValidator.checkForNullReference(assoType, "assoType");

		this.foreignKeyName = foreignKeyName;
		this.assoType = assoType;
	}

	@Override
	protected boolean isValid(Object value)
	{
		if (value == null) {
			return false;
		}

		try {
			Method pi = assoType.getMethod("get"+foreignKeyName);
			String foreignKeyValue = (String)pi.invoke(value);
			return !StringUtils.isEmpty(foreignKeyValue);
		}
		catch (IllegalAccessException e) {
			throw new CefException("","", e, ExceptionLevel.Error);
		}
		catch (InvocationTargetException e) {
			throw new CefException("","", e, ExceptionLevel.Error);
		}
		catch(NoSuchMethodException e){
			throw new CefException("","", e, ExceptionLevel.Error);
		}
	}
}
